<?php

namespace App\Providers;

use App\Models\Config\SystemConfig;
use App\Models\Content\Article;
use App\Policies\ArticlePolicy;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{

    protected $policies = [
        Article::class => ArticlePolicy::class
    ];

    /**
     * Register any application services.
     */
    public function register(): void
    {

    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        $this->loadConfig();

        $this->loadHelpers();
    }

    public function loadHelpers()
    {
        require_once __DIR__.'/../helpers.php';
    }

    /**
     * 从缓存中加载配置，如果没有就去数据库查询然后写入缓存,
     * 缓存永不过期，数据发生变更时后台会主动更新
     */
    public function loadConfig()
    {
        $config = Redis::connection("cache")->get(SystemConfig::class);
        if(!$config){
            $config = SystemConfig::pluck("value",'key')->toArray();
            Redis::connection('cache')->set(SystemConfig::class,json_encode($config));
        }else{
            $config = json_decode($config,true);
        }
        config()->set($config);
    }
}
